var express = require('express');
var router = express.Router();
let upload = require('../util/multer/index')
var moment = require('moment');
const rp = require('request-promise-native');
let { getBase64, setBase64, isgender, FormatData } = require('../util.js');
let { GetopenID_Url, appId, AppSecret, INDEX_RECOMMENDNUM, INDEX_HOTRECOMMENDNUM } = require('../config');
let { isUser, addUser, updataUser, GetUsersById, getbeginMoneyUser, userRecharge, getSwiperList, getSpeedList,
  updataSpeed, addOrder, getOrder, delOrder, getOrderById, updataOrder
} = require('../mysql/users')
/**
 * 所有关于用户的请求接口
 */
const methodsToken = [
  '/userInfoInit',
  '/getbeginMoneyUser',
  '/userRecharge',
  '/addOrder',
  '/getOrder',
  '/delOrder',
  '/updataOrder'
]
router.post("*", (req, res, next) => {
  // 判断token是否存在
  if (methodsToken.indexOf(req.url) >= 0) {
    // 获取用户token
    let userToken = req.headers.token;
    if (!userToken) {
      return res.json({
        code: 0,
        data: "请先登录"
      });
    } else {
      let userId = setBase64(userToken);
      req.body.userId = userId;
    }
  } else {
    let userToken = req.headers.token;
    if (userToken) {
      let userId = setBase64(userToken);
      req.body.userId = userId;
    }
  }
  next();
})
/**
 *  获取openid
 */
router.post('/login', async (req, res, next) => {
  let url = `${GetopenID_Url}appid=${appId}&secret=${AppSecret}&js_code=${req.body.code}&grant_type=authorization_code`;
  let userCode = await rp({
    method: 'GET', url, json: true
  })
  let isUserInfo = await isUser({
    openid: userCode.openid
  })
  if (isUserInfo.length) {
    res.json({
      code: 1,
      data: {
        Token: getBase64(isUserInfo[0].userId)
      }
    })
  } else {
    let data = await addUser({
      openid: userCode.openid
    })
    res.json({
      code: 1,
      data: {
        Token: getBase64(data.insertId)
      }
    })
  }
});
/**
 *   修改初始信息并返回用户信息
 */
router.post('/upinfoLogin', async (req, res, next) => {
  let { nickName, gender, avatarUrl, userId, Token } = req.body;
  userId = setBase64(Token)
  await updataUser(userId, {
    userName: nickName,
    userSex: isgender(gender),
    userUrl: avatarUrl
  })
  let data = await GetUsersById(userId);
  res.json({
    code: 1,
    data
  })
})
/**
 * 同步用户数据
 */
router.post('/userInfoInit', async (req, res, next) => {
  let { nickName, gender, avatarUrl, userId } = req.body;
  await updataUser(userId, {
    userName: nickName,
    userSex: isgender(gender),
    userUrl: avatarUrl
  })
  let data = await GetUsersById(userId);
  res.json({
    code: 1,
    data
  })
})
/**
 * 返回用户信息
 */
router.post('/userInfoById', async (req, res, next) => {
  let { userId } = req.body;
  let data = await GetUsersById(userId);
  res.json({
    code: 1,
    data
  })
})
/**
 * 获取用户余额
 */
router.post('/getbeginMoneyUser', async (req, res, next) => {
  let { userId } = req.body;
  let data = await getbeginMoneyUser(userId)
  res.json({
    code: 1,
    data: data[0]
  })
})
/**
 * 充值
 */
router.post('/userRecharge', async (req, res, next) => {
  let { userId, Money } = req.body;
  let data = await userRecharge(userId, {
    Money
  })
  res.json({
    code: 1,
    data
  })
})
/**
 * 返回首页轮播图数据
 */
router.get('/getSwiperList', async (req, res, next) => {
  let data = await getSwiperList();
  res.json({
    code: 1,
    data
  })
})
/**
 * 获取高铁
 */
router.post('/getSpeedList', async (req, res, next) => {
  let { startRegion, endRegion, speedDate } = req.body;
  let data = await getSpeedList({
    startRegion, endRegion, speedDate
  });
  res.json({
    code: 1,
    data: FormatData(data.data, {
      speedSeat: 'json',
      speedTime: 'hm',
      speedDate: "time"
    }),
    count: data.count
  })
})
/**
 * 添加订单
 */
router.post('/addOrder', async (req, res, next) => {
  let { userId, speedId, pollNum, allPrice, phone, passenger, speedPolleave, speedSeat, seatList } = req.body;
  let [{ beginMoney }] = await getbeginMoneyUser(userId)
  if (Number(allPrice) > Number(beginMoney)) {
    return res.json({
      code: 0,
      data: "你的余额不足"
    });
  }
  await userRecharge(userId, {
    Money: -(allPrice)
  })
  await updataSpeed(speedId, {
    speedPolleave, speedSeat: JSON.stringify(speedSeat)
  })
  await addOrder({
    userId, speedId, pollNum, allPrice, phone, passenger: JSON.stringify(passenger), seatList: JSON.stringify(seatList)
  })
  res.json({
    code: 1,
    data: "添加成功"
  })
})
/**
 * 获取订单
 */
router.post('/getOrder', async (req, res, next) => {
  let { page, limit, userId } = req.body;
  var num = (page - 1) * limit;
  let data = await getOrder(num, limit, { userId });
  data.data = FormatData(data.data, {
    passenger: 'json',
    seatList: 'json',
    speedSeat: 'json',
    speedTime: 'hm',
    speedDate: "time"
  })
  data.data.forEach(item => {
    item.showCancel = false
    if (moment(item.speedDate).isSameOrAfter(moment(), 'day')) {
      if (moment(item.speedDate).isSame(moment(), 'day')) {
        if (moment().isSameOrBefore(moment(item.speedTime, 'HH:mm').subtract(30, 'second'))) {
          item.showCancel = true
        }
      } else {
        item.showCancel = true
      }
    }
  })
  res.json({
    code: 1,
    data: data.data,
    count: data.count
  })
})
/**
 * 删除订单
 */
router.post('/delOrder', async (req, res, next) => {
  let { orderId } = req.body;
  let orderInfo = await getOrderById(orderId)
  orderInfo = FormatData(orderInfo, {
    passenger: 'json',
    seatList: 'json',
    speedSeat: 'json',
    speedTime: 'hm',
    speedDate: "time"
  })
  await userRecharge(orderInfo.userId, {
    Money: orderInfo.allPrice
  })
  let speedPolleave = Number(orderInfo.speedPolleave) + Number(orderInfo.pollNum)
  let speedSeat = orderInfo.speedSeat
  orderInfo.seatList.forEach(sert => {
    speedSeat[sert[0]][sert[1]][sert[2]] = 0
  })
  await updataSpeed(orderInfo.speedId, {
    speedPolleave, speedSeat: JSON.stringify(speedSeat)
  })
  await delOrder(orderId)
  res.json({
    code: 1,
    data: "删除成功"
  })
})
/**
 * 修改订单座位
 */
router.post('/updataOrder', async (req, res, next) => {
  let { speedId, speedSeat, seatList, orderId } = req.body;

  await updataSpeed(speedId, {
    speedSeat: JSON.stringify(speedSeat)
  })

  await updataOrder(orderId, {
    seatList: JSON.stringify(seatList)
  })

  res.json({
    code: 1,
    data: "修改成功"
  })
})

module.exports = router;
